import 'package:flutter/material.dart';
import 'package:flutter_base/config/app_routes.dart';
import 'package:flutter_base/generated/assets.dart';
import 'package:flutter_base/pages/home/model/model_test_psychology.dart';
import 'package:flutter_base/utils/utils_other.dart';
import 'package:flutter_base/utils/utils_widget.dart';
import 'package:flutter_base/widgets/image/auto_image.dart';
import 'package:flutter_base/widgets/image/image_view.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_base/config/app_color.dart';
import 'package:flutter_base/config/app_config.dart';
import 'package:get/get.dart';

/// 测试题卡片组件
class TestCardWidget extends StatelessWidget {
  final ModelTestPsychology model;
  final VoidCallback? onTap;

  const TestCardWidget({
    Key? key,
    required this.model,
    this.onTap,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: () {
        if (onTap == null) {
          Get.toNamed(AppRoutes.testDetail, arguments: {"testId": model.id});
        } else {
          onTap?.call();
        }
      },
      child: Container(
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.circular(20.w),
          boxShadow: [
            BoxShadow(
              color: AppColor.color0C0A09.withOpacity(0.05),
              blurRadius: 10.w,
              offset: Offset(0, 2.w),
            ),
          ],
        ),
        padding: EdgeInsets.symmetric(vertical: 16.w, horizontal: 12.w),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // 头部：测试图标+标题
            _buildHeader(),

            SizedBox(height: 8.w),
            // 标题和描述
            _buildTitleAndDescription(),

            SizedBox(height: 8.w),

            // 参与人数和评分
            // _buildParticipantsAndRating(),
            UtilsWidget.buildParticipantsAndRating(
                (model.userAvatars ?? []), model.total ?? 0),
            const Spacer(),
            // 价格和评分
            UtilsWidget.buildPriceAndRating(
                price: model.price,
                discountPrice: model.discountPrice,
                star: model.star),
            // _buildPriceAndRating(),
          ],
        ),
      ),
    );
  }

  // 头部：图标
  Widget _buildHeader() {
    return Row(
      crossAxisAlignment: CrossAxisAlignment.center,
      children: [
        Container(
          width: 40.w,
          height: 40.w,
          decoration: BoxDecoration(
            color: AppColor.colorDBF1FF,
            borderRadius: BorderRadius.circular(20.w),
          ),
          child: Center(
            child: ImageView(
              imageUrl: model.image ?? AppConfig.testImage,
              width: 24.w,
              height: 24.w,
            ),
          ),
        ),
      ],
    );
  }

  // 标题和描述
  Widget _buildTitleAndDescription() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(
          model.name ?? '未命名测试',
          style: TextStyle(
            fontSize: 14.sp,
            fontWeight: FontWeight.w500,
            color: AppColor.color0C0A09,
          ),
          maxLines: 1,
          overflow: TextOverflow.ellipsis,
        ),
        SizedBox(height: 6.w),
        Text(
          model.desc ?? '暂无描述',
          style: TextStyle(
            fontSize: 12.sp,
            fontWeight: FontWeight.w400,
            color: AppColor.color0C0A09.withOpacity(0.16),
          ),
          maxLines: 1,
          overflow: TextOverflow.ellipsis,
        ),
      ],
    );
  }

  // 参与者头像和人数
  Widget _buildParticipantsAndRating() {
    List<Widget> avatars = [];
    List<String> avatarUrls = (model.userAvatars ?? []).take(3).toList();

    for (int i = 0; i < avatarUrls.length; i++) {
      avatars.add(
        Positioned(
            left: i * 10.w,
            child: ImageView(
              imageUrl: AppConfig.testImage,
              // imageUrl: avatarUrls[i],
              // width: 16.w,
              radius: 8.w,
              border: Border.all(width: 0.5, color: Colors.white),
            )),
      );
    }
    return Row(
      children: [
        // 参与者头像堆叠
        Visibility(
          visible: avatars.isNotEmpty,
          child: SizedBox(
            height: 16.w,
            width: avatars.length == 1
                ? 20.w
                : ((avatars.length - 1) * 6.w + 20.w),
            child: Stack(
              children: avatars,
            ).marginOnly(right: 4.w),
          ),
        ),
        // 参与人数
        Expanded(
            child: Text(
          UtilsOther.formatNumberCard(model.total ?? 0),
          style: TextStyle(
            fontSize: 12.sp,
            fontWeight: FontWeight.w400,
            color: AppColor.color0C0A09,
            letterSpacing: 0.06,
          ),
        )),
      ],
    );
  }

  // 价格和评分
  Widget _buildPriceAndRating() {
    // 获取价格显示文本
    String priceText = _getPriceText();
    String originalPriceText = _getOriginalPriceText();

    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      crossAxisAlignment: CrossAxisAlignment.center,
      children: [
        // 价格部分
        Row(
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            Text(
              priceText,
              style: TextStyle(
                fontSize: 16.sp,
                fontWeight: FontWeight.w600,
                color: priceText == '免费'
                    ? AppColor.color42B969
                    : AppColor.colorFF4D00,
              ),
            ),
            if (originalPriceText.isNotEmpty) ...[
              SizedBox(width: 4.w),
              Text(
                originalPriceText,
                style: TextStyle(
                  fontSize: 10.sp,
                  fontWeight: FontWeight.w400,
                  color: AppColor.color0C0A09.withOpacity(0.16),
                  decoration: TextDecoration.lineThrough,
                ),
              ),
            ],
          ],
        ),

        // 评分
        Row(
          children: [
            AutoImage(
              Assets.commonStar,
              width: 14.w,
            ),
            SizedBox(width: 4.w),
            Text(
              (model.star ?? 0) > 0 ? (model.star! / 10).toString() : '0.0',
              style: TextStyle(
                fontSize: 12.sp,
                fontWeight: FontWeight.w500,
                color: AppColor.color0C0A09,
              ),
            ),
          ],
        ),
      ],
    );
  }

  // 获取价格显示文本
  String _getPriceText() {
    int price = model.price ?? 0;
    if (model.discountPrice != null && model.discountPrice! > 0) {
      price = model.discountPrice!;
    }

    if (price <= 0) {
      return '免费';
    } else {
      return '¥$price';
    }
  }

  // 获取原价显示文本
  String _getOriginalPriceText() {
    int originalPrice = model.price ?? 0;
    if (model.discountPrice != null &&
        model.discountPrice! > 0 &&
        model.discountPrice! < originalPrice) {
      return '¥$originalPrice';
    }
    return '';
  }

// // 格式化数字（如：1200 -> 1.2k）
// String _formatNumber(int number) {
//   if (number >= 1000) {
//     double result = number / 1000;
//     return '${result.toStringAsFixed(1)}k';
//   }
//   return number.toString();
// }
}
